package com.xiaolei.library.common;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;

import com.xiaolei.library.Exts.Ext;

import java.util.HashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 专门做启动界面回数据代理的Fragment
 */
public class ActivityResultFragment extends Fragment implements Observer<ActivityResultFragment.ActivityResultWrapper>
{
    private ResultViewModel viewModel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        viewModel = Ext.create(this, ResultViewModel.class);
        viewModel.liveData.observeForever(this);
    }

    @Override
    public void onChanged(ActivityResultWrapper wrapper)
    {
        if (wrapper != null)
        {
            int requestCode = viewModel.putAndGetRequestCode(wrapper);
            startActivityForResult(wrapper.intent, requestCode, wrapper.bundle);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data)
    {
        ActivityResultWrapper wrapper = viewModel.removeRequestCode(requestCode);
        if (wrapper != null)
        {
            OnActivityResult onActivityResult = wrapper.onActivityResult;
            if (onActivityResult != null)
            {
                onActivityResult.onActivityResult(resultCode, data);
            }
        }
    }

    @Override
    public void onDestroy()
    {
        viewModel.liveData.removeObserver(this);
        viewModel = null;
        super.onDestroy();
    }

    /**
     * 这个类里包含了startActivityForResult所有的需要的参数
     */
    public static class ActivityResultWrapper
    {
        @NonNull
        private Intent intent;
        @Nullable
        private Bundle bundle = null;
        @Nullable
        private OnActivityResult onActivityResult = null;

        public ActivityResultWrapper(@NonNull Intent intent)
        {
            this.intent = intent;
        }

        public ActivityResultWrapper(@NonNull Intent intent, @Nullable Bundle bundle)
        {
            this.bundle = bundle;
            this.intent = intent;
        }

        public ActivityResultWrapper(@NonNull Intent intent, @Nullable Bundle bundle, @Nullable OnActivityResult onActivityResult)
        {
            this.bundle = bundle;
            this.intent = intent;
            this.onActivityResult = onActivityResult;
        }

        public Intent getIntent()
        {
            return intent;
        }

        public void setIntent(Intent intent)
        {
            this.intent = intent;
        }

        public Bundle getBundle()
        {
            return bundle;
        }

        public void setBundle(Bundle bundle)
        {
            this.bundle = bundle;
        }

        public OnActivityResult getOnActivityResult()
        {
            return onActivityResult;
        }

        public void setOnActivityResult(OnActivityResult onActivityResult)
        {
            this.onActivityResult = onActivityResult;
        }
    }

    /**
     * 真正执行的回调
     */
    public static interface OnActivityResult
    {
        public void onActivityResult(int resultCode, @Nullable Intent data);
    }

    /**
     * 对应本fragment所使用的ViewModel
     */
    public static class ResultViewModel extends ViewModel
    {
        private AtomicInteger reqCode = new AtomicInteger(1);
        private HashMap<Integer, ActivityResultWrapper> reqStore = new HashMap<>();

        /**
         * 将包装类存入库中，并且把RequestCode返回
         *
         * @param wrapper
         * @return
         */
        public int putAndGetRequestCode(ActivityResultWrapper wrapper)
        {
            int requestCode = reqCode.incrementAndGet();
            while (requestCode >= 65535)
            {
                reqCode.set(1);
                requestCode = reqCode.incrementAndGet();
                while (reqStore.containsKey(requestCode))
                {
                    requestCode = reqCode.incrementAndGet();
                }
            }
            reqStore.put(requestCode, wrapper);
            return requestCode;
        }

        /**
         * 移除并且返回对应的数据
         *
         * @param requestCode
         * @return
         */
        public ActivityResultWrapper removeRequestCode(int requestCode)
        {
            return reqStore.remove(requestCode);
        }

        @Override
        protected void onCleared()
        {
            reqStore.clear();
            super.onCleared();
        }

        public MutableLiveData<ActivityResultWrapper> liveData = new MutableLiveData<>();
    }
}
